package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.BasicInfomationInterface;
import com.bridgetree.jubaocrm.util.GroupsBasicInformation;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Mmember;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
/**
 *基本信息
 */
public class GroupsBasicInformationActivity extends Activity {
	private final String TAG ="GroupsBasicInformationActivity";
	private Context mContext;
	private ListView xm_bi_lv = null;
	private GroupsBasicInformationAdapter mGroupsBasicInformationAdapter = null;
//	private ArrayList<HashMap<String,Object>> proInfoListData = null;
	private Projects mProjects;
	private List<String> names;
	private TextView xm_bi_tv_title;
	private String user_id =""; 
	private String token ="";
	private GroupsBasicInformation mGroupsBasicInformation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_basic_information);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("Projects");
		}
		
		xm_bi_tv_title=(TextView)findViewById(R.id.xm_bi_tv_title);
		xm_bi_tv_title.setText("基本信息");
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		xm_bi_lv = (ListView)findViewById(R.id.xm_bi_lv);
		if(mProjects!=null){
			getBasicInfomation(1);
		}

		names =new ArrayList<String>();
		names.add("中文名");
		names.add("英文名");
		names.add("国家");
		names.add("地址");
		names.add("城市");
		names.add("重要程度");
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	/**
	 * 获取基本信息
	 */
	private void getBasicInfomation(final int pageindex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
//			http://crmsoap.woniuwo.cn/client?cid=537563ffd5ac700e4ce8f610
			//&part=c&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl&page=1
			String URL = Network.API_DOMAIN+"/client?cid="+mProjects.getClient_id() +
			"&part=c&user_id="+user_id+"&token="+token+
			"&validation="+CRMUserBaseInfo.kValication+"&page="+pageindex;

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  
					Request.Method.GET,   
					URL,   
					null,  
					new Response.Listener<JSONObject>() {  
						@Override  
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("获取基本信息1 response=" + response);
							try {
								//							System.out.println("response="+response);   
								if (!response.isNull("client")) {
									String project = response.get("client").toString();
									mGroupsBasicInformation = new GroupsBasicInformation();
									JSONObject jsonObj2 = new JSONObject(project);
									if (!jsonObj2.isNull("is_exclusive")) {
										String is_exclusive = jsonObj2.getString("is_exclusive");
										mGroupsBasicInformation.setIs_exclusive(is_exclusive);
									}
									if (!jsonObj2.isNull("address")) {
										String address = jsonObj2.getString("address");
										mGroupsBasicInformation.setAddress(address);
									}
									if (!jsonObj2.isNull("import_level")) {
										String import_level = jsonObj2.getString("import_level");
										mGroupsBasicInformation.setImport_level(import_level);
									}
									if (!jsonObj2.isNull("group_id")) {
										String group_id = jsonObj2.getString("group_id");
										mGroupsBasicInformation.setGroup_id(group_id);
									}
									if (!jsonObj2.isNull("client_id")) {
										String client_id = jsonObj2.getString("client_id");
										mGroupsBasicInformation.setClient_id(client_id);
									}
									if (!jsonObj2.isNull("english_name")) {
										String english_name = jsonObj2.getString("english_name");
										mGroupsBasicInformation.setEnglish_name(english_name);
									}
									if (!jsonObj2.isNull("country")) {
										String country = jsonObj2.getString("country");
										mGroupsBasicInformation.setCountry(country);
									}
									if (!jsonObj2.isNull("chinese_name")) {
										String chinese_name = jsonObj2.getString("chinese_name");
										mGroupsBasicInformation.setChinese_name(chinese_name);
									}
									if (!jsonObj2.isNull("city")) {
										String city = jsonObj2.getString("city");
										mGroupsBasicInformation.setCity(city);
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
								////over
								mGroupsBasicInformationAdapter = new GroupsBasicInformationAdapter(GroupsBasicInformationActivity.this,mGroupsBasicInformation,names);
								xm_bi_lv.setAdapter(mGroupsBasicInformationAdapter);
								
								
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}  
					},   
					new Response.ErrorListener() {  
						@Override  
						public void onErrorResponse(VolleyError arg0) {  
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}

	}

}

class GroupsBasicInformationAdapter extends BaseAdapter {
	private List<String> names;
	private GroupsBasicInformation mProjects = null;
	private LayoutInflater listContainer; // 视图容器

	public final class ListItemView { // 自定义控件集合
		public TextView xm_12_item_title; 
		public TextView xm_12_item_content; 
	}

	public GroupsBasicInformationAdapter(Context mContext, GroupsBasicInformation mGroupsBasicInformation,List<String> names) {
		this.mProjects = mGroupsBasicInformation;
		this.names = names;
		listContainer = (LayoutInflater) mContext
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		if (mProjects != null) {
			return 6;
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		if (convertView == null) {
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(R.layout.xm_basic_info_item, null);
			// 获取控件对象
			listItemView.xm_12_item_title = (TextView) convertView.findViewById(R.id.xm_12_item_title);
			listItemView.xm_12_item_content = (TextView) convertView.findViewById(R.id.xm_12_item_content);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		switch (position) {
		case 0:
			listItemView.xm_12_item_title.setText(names.get(0));
			String cname = mProjects.getChinese_name().toString().trim();
			listItemView.xm_12_item_content.setText(cname);
			if(cname.length()>22){
				listItemView.xm_12_item_content.setGravity(Gravity.CENTER);
			}
			break;
		case 1:
			listItemView.xm_12_item_title.setText(names.get(1));
			String ename = mProjects.getEnglish_name().toString().trim();
			listItemView.xm_12_item_content.setText(ename);
			if(ename.length()>22){
				listItemView.xm_12_item_content.setGravity(Gravity.CENTER);
			}
			break;
		case 2:
			listItemView.xm_12_item_title.setText(names.get(2));
			String country = mProjects.getCountry().toString().trim();
			listItemView.xm_12_item_content.setText(country);
			if(country.length()>22){
				listItemView.xm_12_item_content.setGravity(Gravity.CENTER);
			}
			break;
		case 3:
			listItemView.xm_12_item_title.setText(names.get(3));
			String address = mProjects.getAddress().toString().trim();
			listItemView.xm_12_item_content.setText(address);
			if(address.length()>22){
				listItemView.xm_12_item_content.setGravity(Gravity.CENTER);
			}
			break;
		case 4:
			listItemView.xm_12_item_title.setText(names.get(4));
			String city = mProjects.getCity().toString().trim();
			listItemView.xm_12_item_content.setText(city);
			if(city.length()>22){
				listItemView.xm_12_item_content.setGravity(Gravity.CENTER);
			}
			break;
		case 5:
			listItemView.xm_12_item_title.setText(names.get(5));
			String number = mProjects.getImport_level();
			String tmp ="一般";
//			@"一般",@"0",@"中等",@"1",@"重要",@"2",@"非常重要",@"3"
			if(number.equals("0")){
				tmp ="一般";
			}else if(number.equals("1")){
				tmp ="中等";
			}else if(number.equals("2")){
				tmp ="重要";
			}else if(number.equals("3")){
				tmp ="非常重要";
			}
			listItemView.xm_12_item_content.setText(tmp);
			break;
		}
		return convertView;
	}

}
